function DrawTablebymenu(columns){
	createTableblock(columns);
}
function losResTable(){
	var data = { func : "LoadPOSguestTable"};
	var url = "/POSgenerateOrderService";
	simpleservice(url,data,function(data){
		var objArray = JSON.parse(data);
		SharedData.POSReservationTable = objArray;
		createTableblock(null);
	});
}
function selectedZone(e){
	$('input[filId]').attr('class','content2buttonL btn');
	$(e).attr('class','content2buttonL btn selectbtn');
	var lefId =$(e).attr('filId');
	filterTable(lefId);
}

function filterTable(lefId){
	var table =SharedData.Table;
	var tableAry = [];
	if(lefId != "allTable"){
		for(var i=0;i<table.length;i++){
			if(table[i].zoneString == lefId){
				tableAry.push(table[i]);
			}
		}
		SharedData.filterTable = tableAry;
	}else{
		SharedData.filterTable = table;
	}
	var col = Math.ceil($('[name=Block]').width()/226);
	var PresTable =SharedData.POSReservationTable;
	createTableblock(col-1);
}

function createTableblock(columns){
	var TableAmt ="";(SharedData.filterTable!=null)?TableAmt =[].concat(SharedData.filterTable):TableAmt =[].concat(SharedData.Table);
	TableAmt.sort(function(a, b) {return a.tableTitle.localeCompare(b.tableTitle)})
	
	var column = (columns>1)?columns:6;
	var objArrays = SharedData.POSReservationTable.slice();
		objArrays.sort(function(a, b) {
			return a.tableId - b.tableId;});
	var elmTable="";
	var n=0
	var pWidth=$('.TapContent1').width();
	var row =Math.ceil(TableAmt.length/column);
	var talDelAry =[];
	$('.Table_Pos').css('width',pWidth/column);
	$('[name=AllTable_pos]').find("*").remove();
	
	for(var i =0;i<row;i++){
		elmTable+='<tr>';
		for( n=0;n<TableAmt.length;n++){
			if(n<column){
				elmTable+='<td name="elmTable"><div class="Table_Pos" tableId="'+TableAmt[n].id+'">&nbsp;'+TableAmt[n].tableTitle+'</div></td>';
				 talDelAry.push(TableAmt[n].id);
			}else{
				for(var b=0;b<TableAmt.length;b++){
					for(var a =0;a<talDelAry.length;a++){
						if(TableAmt[b].id==talDelAry[a]){
							TableAmt.splice(b,1);
						}
					}
				}
				break;
			}
		}
		 if(TableAmt.length-talDelAry.length != 0){
			 if((column-n)!=0){
				 for(var i = 0;i<column-Math.ceil(TableAmt.length/column);i++){
					 elmTable+='<td name="elmTable">&nbsp;</td>';
				 }
			 }
		 }
		elmTable+='</tr>';
	}
	var menuAndTaskWidth = $("[name=leftMenu]:visible").width() + $("[name=taskList]:visible").width();
	if(menuAndTaskWidth > 0) menuAndTaskWidth += 3;
	$("[name=AllTable],[for=pageload]").css("width","calc(100% - "+menuAndTaskWidth+"px)");
	$('[name=AllTable_pos]').append("<table style='width:100%'>"+elmTable+"</table>");
	$('[name=AllTable_pos]').find("table tr:first").find("td").css("width",(100/column) + "%");
	$('.detailicon').removeClass("rightItem");
	fillPOSResTable();
	attachTableEvent();
	attachOtherButtonEvent();
	arrangeTab();
	RightClickDialog();
	$('.detailicon').addClass("rightItem");
}

function fillPOSResTable(){
	var displayTables = $("[name=elmTable] .Table_Pos");
	for(var i=0;i<displayTables.length;i++){
		var displayTable = $(displayTables[i]);
		var tableid = displayTable.attr("tableid");
		var table = getObjectFromSharedData(SharedData.Table,tableid);
		displayTable.html("");
		var Ary = [];
		for(var a=0;a<SharedData.POSReservationTable.length;a++){
			if(SharedData.POSReservationTable[a].tableId == tableid){
				var obj = SharedData.POSReservationTable[a];
				var hours = new Date(obj.Arrivel).getHours();
				var minutes =new Date(obj.Arrivel).getMinutes();
				var ampm = hours >= 12 ? 'pm' : 'am';
				var gname=(obj.Name!=null)?obj.Name:'';
				var backgroungSat =(obj.Status != "R")?"satusworkin":"satusRes";
				var aryText = (obj.Arrivel!=null)?'<div posResId="'+obj.id+'" class="elmresTableheight '+backgroungSat+'" resStatus="'+obj.Status+'" haveorder="'+obj.haveOrder+'"><div class="detailicon"><div class="header_eem_icon tabledetail_icon"></div></div><div style="fo"></div>'+
					'&nbsp;<span class="tbName">'+table.tableTitle+'</span>'+
					'<span class="tbArr" timeArrivel="'+obj.Arrivel+'">Arr. '+hours+":"+minutes+" "+ampm+'</span>':'';
					aryText+='<div class="tbBody" >'+gname+'</div>';
					aryText+=(obj.tel!=null)?'<div class="tbBody" >'+obj.tel+'</div>':'';
					
					aryText+=(obj.money!= 0)?'<div class="money">'+toCurrencyString(obj.money,false)+'</div>':'';
				Ary.push(aryText);
			}
		}
		var rs = sortResOrder(Ary);
		displayTable.html(rs);
		if(displayTable.html()=="") displayTable.html("&nbsp;"+table.tableTitle);
	}
}

function sortResOrder(Ary){
	var domR =[];
	var domW =[];
	if(Ary.length==1){
	 return Ary.toString();
	}
	for(var i = 0;i<Ary.length;i++){
		if($(Ary[i]).attr('resstatus') =="W"){
			var editAry = $('<div>'+Ary[i]+'</div>').find('[posresid]').removeClass( "elmresTableheight");
			var editAryp = editAry.addClass( "elmresTableheight2");
			domW.push(editAryp.prop('outerHTML'));
		}else{
			var editAry = $('<div>'+Ary[i]+'</div>').find('[posresid]').removeClass( "elmresTableheight");
			var	editAryp = editAry.addClass( "elmresTableheight2");
			domR.push(editAryp.prop('outerHTML'));
		}
	}
	var strText = domR.toString()+domW.toString();
	return strText;
}

function savePOSReservation(){
	if($("[name=guestName]:visible").val()==""){showWerningpopUp(); return;}
	if($("[name=phoneNumber]:visible").val()==""){showWerningpopUp(); return;}
	if($("[name=arriveH]:visible").val()==""){showWerningpopUp(); return;}
	if($("[name=arriveM]:visible").val()==""){showWerningpopUp(); return;}
	var name=$("[name=guestName]:visible").val()+" "+$("[name=guestLastName]:visible").val();
	var tel=$("[name=phoneNumber]:visible").val();
	var table=$('[name=ResPOSTable]:visible').parents('#BlankDialog').attr('tableId');
	var dateArrive =getDate().toSystemFormat()+" "+$("[name=arriveH]:visible").val()+":"+$("[name=arriveM]:visible").val();
	var guest=$('[name=guestAmt_POS_res]:visible').val();
	var note=$('[name=note_POS_res]:visible').val();
	var link = "/POSgenerateOrderService?func=CreatePOSguestTable&tableId="+table+"&gName="+name
	+"&timeA="+dateArrive+"&guestTel="+tel+"&guestAmt="+guest+"&note="+note;
	simpleserviceWithArgs(link,null,savePOSReservationSuccess,null);
	waitingDialog({});
}

function showWerningpopUp(){
	var conntent='<div class="header_eem_icon werningRes_icon" style="display:table-cell;"></div><div style="display:table-cell;">'+werningHead+'</div>';
	conntent+='<div>'+werningMassage+'</div>';
	var button=[{title:"Yes" , callback: function(thisdialog,args){
		$("[id='BlankDialog'][scrolltop]").dialog("close");
	}},
		{title:"No", callback: function(thisdialog,args){
			$("[id='BlankDialog'][scrolltop]").dialog("close");
		}}];
	customDialog(null,conntent,{width:400},button,null);
	$('.ui-newdialog-content').css('width','300px');
}

function savePOSReservationSuccess(data,obj){
	$("[id='BlankDialog'][scrolltop]").dialog("close");
	var objArray = JSON.parse(data);
	if(objArray.length==0){
		simpleDialog("save file !!",100);
		closeWaitingDialog();
	}else{
		var checkLogOut = checkSessionPOS(objArray);
		if(checkLogOut)
			return;
		var resTable= SharedData.POSReservationTable;
		resTable.push(objArray);
		createTableblock(null);
		closeWaitingDialog();
	}
}

function RightClickDialog(){
	$(document).on('contextmenu', function(e) {
		if ($(e.target).is($('.Table_Pos'))){ return false; }
		if($(e.target).parents('.Table_Pos').size()!=0){ return false; }
		if($(e.target).parents('#BlankDialog[type=RightClick]:first').size()!=0){ return false; }
		$("[id='BlankDialog'][type=RightClick]").dialog("close");
	});
	$('.Table_Pos').mousedown(function(e){
		if( e.button == 2 ){
			var traget=$(this);
			($(event.target).attr('posresid')!=null)?traget=$(event.target):'';
			$("[id='BlankDialog'][type=RightClick]").dialog("close");
			var position = ((traget.offset().top - $(document).scrollTop()) > ($(window).height()/2))?"bottom":"top";
			var dialog = dynamicLoadingCursorRightClickDialog(position,traget,"/POS/dialog/rightClickDialog.jsp",checktoCreateRightClickMenu,$(event.target));
			return false; 
		} 
		return true; 
	});
}

function checktoCreateRightClickMenu(e,t){
	var tableId = (t.attr('tableid')==null)?t.parents('[tableid]').attr('tableid'):t.attr('tableid');
	var status=(t.attr('resstatus')==null)?t.parents('[posresid]').attr('resstatus'):t.attr('resstatus');
	var haveOrder=(t.attr('haveorder')==null)?t.parents('[posresid]').attr('haveorder'):t.attr('haveorder');
	$('.ui-newdialog-content').css('padding','0');
	e.parent().css('width','200px');
	e.find('[name=ResPOSTable]').css('display','none');
	var menu_one='<div name="menu_one">'+menu_R_one+'</div>';
	var menu_two='<div name="menu_two">'+menu_R_two+'</div>';
	var menu_three='<div name="menu_three">'+menu_R_three+'</div>';
	var menu_four='<div name="menu_four">'+menu_R_four+'</div>';
	var menu_five='<div name="menu_five">'+menu_R_five+'</div>';
	var menu_six='<div name="menu_six">'+menu_R_six+'</div>';
	var menu_seven='<div name="menu_seven">'+menu_R_seven+'</div>';
	var menu_eight='<div name="menu_eight">'+menu_R_eight+'</div>';
	var menu_nine='<div name="menu_nine">'+menu_R_nine+'</div>';
	var checkTable = t.parents('td').find('[posresid]').attr('posresid');
	var strMenu="";
	e.find('[name=posRightClickmenu]').children().remove();
	e.removeAttr("tableId");
	if(checkTable!=null){
		strMenu+=(haveOrder=="true")?menu_eight:"";
		strMenu+=(haveOrder=="true")?menu_nine:"";
		strMenu+=($(t).parents('td').find('[resstatus=R]').size()==0)?menu_two:"";
		if(status!="R"){
			strMenu+=menu_five+menu_four;
			//e.parent().css('height','140px');
		}else{
			strMenu+=menu_seven+menu_six+menu_five+menu_three;
			//e.parent().css('height','115px');
		}
		e.find('[name=posRightClickmenu]').append(strMenu);
		
	}else{
		strMenu+=menu_one;
		e.find('[name=posRightClickmenu]').append(strMenu);
		
	}
	reLocateCursorRightClickDialog(null,null,e);
	RightClickAction(e,tableId,t);
}

function RightClickAction(e,tableId,table){
	var resId = (table.attr('posresid')==null)?table.parents('[posresid]').attr('posresid'):table.attr('posresid');
	$('[name=menu_one],[name=menu_two]').click(function(){
		e.find('[name=posRightClickmenu]').hide();
		e.find('.ui-newdialog-button').show();
		e.find('.ui-newdialog-button').children(':first').css('left','50%');
		e.find('.ui-newdialog-button').children(':first').css('width','340px');
		e.find('.ui-newdialog-titlebar').show();
		e.parent().css('height','auto');
		e.parent().css('width','500px');
		e.find('[name=ResPOSTable]').show();
		var headtext='<span name="tableName">'+getObjectFromSharedData(SharedData.Table,tableId).tableTitle+'|</span>'+
			'<span class="forReshead">'+res_R+'</span>'+
			'<span><input type="checkbox" name="addtask"/>'+add_t+'<span>';
		$('.ui-newdialog-titlebar .colse_icon').before(headtext);
			var button=[{title:btnres , callback: function(thisdialog,args){
				savePOSReservation();
			}},
				{title:btncancel , callback: function(thisdialog,args){
					$("[id='BlankDialog'][scrolltop]").dialog("close");
				}}];
		bindButtonDialog(e,button,null);
		e.attr("tableId",tableId);
	});
	$('[name=menu_six]').click(function(){
		e.find('[name=posRightClickmenu]').hide();
		e.find('.ui-newdialog-button').show();
		e.find('.ui-newdialog-button').children(':first').css('left','50%');
		e.find('.ui-newdialog-button').children(':first').css('width','340px');
		e.find('.ui-newdialog-titlebar').show();
		e.parent().css('height','auto');
		e.parent().css('width','500px');
		e.find('[name=ResPOSTable]').show();
		var headtext='<span name="tableName">'+getObjectFromSharedData(SharedData.Table,tableId).tableTitle+'|</span>'+
			'<span class="forReshead">'+res_R+'</span>'+
			'<span><input type="checkbox" name="addtask"/>'+add_t+'<span>';
		$('.ui-newdialog-titlebar .colse_icon').before(headtext);
			var button=[{title:btnres , callback: function(thisdialog,args){
				editPOSGuest(resId);
				$("[id='BlankDialog'][scrolltop]").dialog("close");
			}},
				{title:btncancel , callback: function(thisdialog,args){
					$("[id='BlankDialog'][scrolltop]").dialog("close");
				}}];
		bindButtonDialog(e,button,null);
		e.attr("tableId",tableId);
		var resData = getObjectFromSharedData(SharedData.POSReservationTable,resId);
		$('[name=guestName]:visible').val(resData.Name.split(" ")[0]);
		$('[name=guestLastName]:visible').val(resData.Name.split(" ")[1]);
		$('[name=phoneNumber]:visible').val(resData.tel);
		$('[name=arriveH]:visible').val(new Date(resData.Arrivel).getHours());
		$('[name=arriveM]:visible').val(new Date(resData.Arrivel).getMinutes());
		$('[name=guestAmt_POS_res]:visible').val(resData.guest);
		$('[name=note_POS_res]:visible').text(resData.note);
	
	});
	$('[name=menu_seven]').click(function(){
		loadDynamicJSP($("div[for=pageload]"),"/POS/OrderItem.jsp",waitingDialog,function(resp,obj){
			$("[id='BlankDialog'][scrolltop]").dialog("close");
			closeWaitingDialog();
			SelectTab(tableId);
			delete getCurrentTable().OwnerTable;
		},{dom:table});
	});
	$('[name=menu_three]').click(function(){
	var resId = (table.attr('posresid')==null)?table.parents('[posresid]').attr('posresid'):table.attr('posresid');
	var tableName =getObjectFromSharedData(SharedData.Table,tableId).tableTitle;
	e.find('[name=posRightClickmenu]').hide();
	e.find('.ui-newdialog-button').show();
	e.find('.ui-newdialog-button').children(':first').css('left','50%');
	e.find('.ui-newdialog-button').children(':first').css('width','340px');
	e.find('.ui-newdialog-titlebar').show();
	e.parent().css('height','auto');
	e.parent().css('width','500px');
	e.find('[name=POS_cancel_res]').show();
	var headtext='<span name="tableName">'+tableName+'|</span>'+
		'<span class="forReshead">'+cancelres+'</span>';
	$('.ui-newdialog-titlebar .colse_icon').before(headtext);
		var button=[{title:btncanresCancel , callback: function(thisdialog,args){
			$("[id='BlankDialog'][scrolltop]").dialog("close");
		}},
			{title:btncanresSave , callback: function(thisdialog,args){
				cancelPOSreservation(resId);
				$("[id='BlankDialog'][scrolltop]").dialog("close");
			}}];
	bindButtonDialog(e,button,null);
	e.attr("tableId",tableId);
	fillPOSCancelReason();
	$('[name=tableNames]').text(' '+tableName);
	$('[name=owner_of_table]').text(getObjectFromSharedData(SharedData.POSReservationTable,resId).Name);
	});
	$('[name=menu_nine]').click(function(){
		openOrderListPage(resId);
	});
	$('[name=menu_eight]').click(function(){
		var tab = SelectTab(tableId,null,false);
		tab.pagetitle = "payment";
		switchTab($("#tabs [table="+tab.table.id+"]"),{posresid:resId});
	});
	$('[name=menu_five]').click(function(){moveResTable(this,resId)});
}

function editPOSGuest(resid){
	var name=$("[name=guestName]:visible").val()+" "+$("[name=guestLastName]:visible").val();
	var tel=$("[name=phoneNumber]:visible").val();
	var table=$('[name=ResPOSTable]:visible').parents('#BlankDialog').attr('tableId');
	var dateArrive =getDate().toSystemFormat()+" "+$("[name=arriveH]:visible").val()+":"+$("[name=arriveM]:visible").val();
	var guest=$('[name=guestAmt_POS_res]:visible').val();
	var note=$('[name=note_POS_res]:visible').val();
	var link = "/POSgenerateOrderService?func=EditPOSguestTable&resId="+resid+"&gName="+name
	+"&timeA="+dateArrive+"&guestTel="+tel+"&guestAmt="+guest+"&note="+note;
	simpleserviceWithArgs(link,null,editPOSGuestSuccess,null);
	waitingDialog({});
}

function editPOSGuestSuccess(data,obj){
	$("[id='BlankDialog'][scrolltop]").dialog("close");
	var objArray = JSON.parse(data);
	if(objArray.length==0){
		simpleDialog("save file !!",100);
		closeWaitingDialog();
	}else{
		var resTable= getObjectFromSharedData(SharedData.POSReservationTable,objArray.id);
		resTable.Arrivel = objArray.Arrivel;
		resTable.Name = objArray.Name;
		resTable.guest =objArray.guest ;
		resTable.note =objArray.note ;
		resTable.tel = objArray.tel;
		createTableblock(null);
		closeWaitingDialog();
	}
}

function cancelPOSreservation(resid){
	var reason=$("[name=POS_cancel_reason]:visible").val();
	var detail=$('[name=detail_POS_cancelres]:visible').val();
	var link = "/POSgenerateOrderService?func=AddPOSReasonCancel&Posresid="+resid+"&reason="+reason
	+"&detail="+detail;
	simpleserviceWithArgs(link,null,cancelPOSreservationSuccess,null);
	waitingDialog({});
}

function cancelPOSreservationSuccess(data,obj){
	$("[id='BlankDialog'][scrolltop]").dialog("close");
	var objArray = JSON.parse(data);
	if(objArray==0){
		simpleDialog("save file !!",100);
		closeWaitingDialog();
	}else{
		var index= SharedData.POSReservationTable.indexOf(getObjectFromSharedData(SharedData.POSReservationTable,objArray));
		SharedData.POSReservationTable.splice(index,1);
		createTableblock(null);
		closeWaitingDialog();
	}
}

function attachOtherButtonEvent(){
	$("input[type=button][value='Take Away']").click(function(){
		loadDynamicJSP($("div[for=pageload]"),"/POS/OrderItem.jsp",waitingDialog,function(resp,obj){
			closeWaitingDialog();
			SelectTab("TakeAway","Take Away");
		},{dom:$(this)});
	});
}

function fillPOSCancelReason(){
	var selected = $("[name=POS_cancel_reason]:visible");
	selected.find("option").remove();
	selected.append("<option value=''>"+simpleLabel_Select+"</option>");
	for(var i=0;i<SharedData.CancelReason.length;i++)
		selected.append("<option value='"+SharedData.CancelReason[i].id+"'>"+SharedData.CancelReason[i].reason+"</option>");
	selected.val(0);
}